'use strict';

/**
 * 主入口程序
 */
const Koa = require('koa');
// const enforceHttps = require('koa-sslify');
const bodyParser = require('koa-bodyparser');
const mountRoutes = require('mount-koa-routes');
const cors = require('koa2-cors');
const publicIp = require('public-ip');
const globalConfig = require('./config/global_config');
const FileUtil = require('./src/utils/file_util');
const path = require('path');
const koaStatic = require('koa-static') 

// 初始相关文件路径
initFilePath();

// 初始化相关模块
const configCtrl = require('./src/controllers/config');
require('./src/utils/mongodb').connect(mongodb_callback); // init mongodb
const guardCtrl = require('./src/controllers/guard');
const strangerPush = require('./src/controllers/stranger_push');
const liveness = require('./src/controllers/liveness');
const record = require('./src/controllers/record');


const redisSubscribe = require('./src/utils/redis_subscribe');
redisSubscribe.init([guardCtrl.push_config, strangerPush.push_config, record.process]);
redisSubscribe.add_filter(liveness.check_filter);

require('./src/controllers/attendance').init(); // 注册定时任务加工考勤数据

const app = new Koa();

// 因为前端浏览器暂时不能访问自制证书的https，所以先放弃https。同时建议https可以加载nginx层。
// Force HTTPS on all page
// app.use(enforceHttps());

// 静态资源
app.use(koaStatic(path.join(__dirname,'./res')));

// cors处理跨域
app.use(cors({
    origin: function (ctx) {
        // if(process.env.NODE_ENV==='production'){
        //     const public_ip = await publicIp.v4()
        //     return public_ip
        // }
        return globalConfig.public_cors_origin;
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));

// parse request body:
app.use(bodyParser({
    "formLimit": "5mb",
    "jsonLimit": "5mb",
    "textLimit": "5mb"
}));

// middleware
app.use(require('./src/middlewares/response'));
app.use(require('./src/middlewares/interceptor'));

// 定时任务
const timedFn = require('./src/timed/timed.task');
timedFn()

// auto mount routes with routes_folder_path, 'false': dont dump list
mountRoutes(app, require('path').join(__dirname, 'src', 'routes'), false);

// 提供给设备的服务
app.use(require('./src/common/device_server').routes())

// Node全局异常捕获
process.on('uncaughtException', function (err) {
    console.error('An uncaught error occurred!')
    console.error(err.stack)
    // Recommend: restart the server
});

/**
 * 初始化相关目录
 */
function initFilePath() {
    // 创建log目录
    FileUtil.mkdirsSync(globalConfig.log_dir);

    // 创建相关res目录
    FileUtil.mkdirsSync(globalConfig.res.avatar_dir);
    FileUtil.mkdirsSync(globalConfig.res.capture_dir);
    FileUtil.mkdirsSync(globalConfig.res.uploader_dir);
    FileUtil.mkdirsSync(globalConfig.res.downloadlog_dir);
    FileUtil.mkdirsSync(globalConfig.res.julong_record_dir);
}

async function mongodb_callback() {
    configCtrl.dbCallback();
    require('./src/controllers/account').init();
    require('./src/controllers/config').init();
}

module.exports = app;
